import React, { useEffect, useState } from 'react';
import {Button,Table,Switch,notification,Tag,Drawer,Form,Input,Select,Tree} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table';
import service from '../../../api'
// import "./Swiper.scss"
import _ from 'lodash'//lodash是一个常用工具函数集合库
import { useNavigate } from 'react-router-dom';
import type { DataNode } from 'antd/es/tree';

interface Props {}

function Admin(props:Props) {
    
    var navigate = useNavigate() 

    var [adminlist , setAdminlist] = useState([])
    var [pagination , setPagination] = useState({current:0,pageSize:0})
    var [open , setOpen] = useState(false);
    var [checkedKeys , setCheckedKeys] = useState([]);
    var [adminid , setAdminid] = useState('');
    var [loading , setLoading] = useState(false);

    const [form] = Form.useForm();

    //请求轮播图列表
    var request_admin_list = async ()=>{
        setLoading(true);
        var res = await service.admin.admin_list();
        setLoading(false);
        setAdminlist(res.data.data)
    }
    useEffect(()=>{
        request_admin_list()
    },[])

    interface DataType {
        key: string;
        adminid: string;
        checkedKeys: string[];
        adminname: string;
        role: number;
    }

    //切换展示状态
    var handleChange = async (checked:any,bannerid:any)=>{
        var res = await service.banner.banner_updateFlag({ bannerid,flag:checked });
        if( res.data.code == 200 ){
            notification.success({message:'更新flag成功!'})
        }
    }

    //显示编辑框
    var handleEdit = (values:any)=>{
        setOpen(true);//弹出抽屉
        form.setFieldsValue(values);//回显表单数据
        setCheckedKeys( values.checkedKeys ) //设置checkedKeys的值
        setAdminid( values.adminid ) //保存adminid
    }
    //删除管理员
    var handleDelete = async (adminid:any)=>{
        //删除远程图片
        var res = await service.banner.banner_delete({ adminid });
        if( res.data.code == 200 ){
            notification.success({message:'删除图片成功!'});
            //删除本地图片
            var index = adminlist.findIndex((item:any)=>item.adminid == adminid)
            if( index != -1 ){
                //对本地数据深拷贝( 否则组件不会更新 )
                //var newadminlist = JSON.parse( JSON.stringify( adminlist ) )
                var newadminlist = _.cloneDeep(adminlist);
                newadminlist.splice(index,1);
                setAdminlist( newadminlist );
            }
        }
    }

    //跳转到添加轮播图页面
    var showDrawer = ()=>{
        setOpen(true);
    }

    //分页时执行
    var onPageChange = (pagination:any)=>{
        setPagination( pagination )
    }

    //关闭抽屉时执行
    var onClose = ()=>{
        setAdminid('');//重置adminid
        form.setFieldsValue({adminname:'',password:'',role:null,checkedKeys:[]});//回显表单数据
        setCheckedKeys([]);
        setOpen(false);
    }

    //表单验证通过执行
    const onFinish = async (values: any) => {
        if( adminid ){
            var res = await service.admin.admin_update( values );
            if( res.data.code == 200 ){
                notification.success({message:'编辑管理员成功!'});
                setOpen(false);
            }
        }else{
            var res = await service.admin.admin_add( values );
            if( res.data.code == 200 ){
                notification.success({message:'新增管理员成功!'});
                setOpen(false);
            }
        }
    };

    //树形控件中的选择发生改变
    const onCheck = (checkedKeysValue: any) => {
        console.log('onCheck', checkedKeysValue);
        setCheckedKeys( checkedKeysValue );//保存选中的权限
        form.setFieldValue('checkedKeys',checkedKeysValue) //保存选中的权限到form组件的中checkedKeys属性中
    };

    //表格列的配置项
    const columns: ColumnsType<DataType> = [
        {
          title: '序号',
          key: 'name',
          render: (_,record,index) => <div>{ (pagination.current-1) * pagination.pageSize + index+1}</div>,
        },
        {
          title: '账号',
          key: 'adminname',
          width: 200,
          dataIndex:'adminname'
        },
        {
          title: '权限',
          key: 'name',
          render: (_,record,index) => <Tag color="#87d068"> { record.role == 1 ? '管理员' : '超级管理员' } </Tag>,
        },
        {
          title: '操作',
          key: 'name',
          render: (_,record,index) => <>
            <Button style={{marginRight:10}} type="primary" onClick={()=>{ handleEdit(record) }}> Edit </Button>
            <Button danger type="primary" onClick={()=>{ handleDelete(record.adminid) }}> Delete </Button>
          </>,
        },
    ];

    //树形控件的数据源
    const treeData: DataNode[] = [
        {
          title: '首页',
          key: '0'
        },
        {
          title: '轮播图管理',
          key: '1',
          children: [
            { title: '轮播图列表', key: '1-1' },
          ],
        },
        {
          title: '账号管理',
          key: '2',
          children: [
            { title: '管理员列表', key: '2-1' }
          ],
        },
        {
          title: '产品管理',
          key: '3',
          children: [
            { title: '产品列表', key: '3-1' },
            { title: '秒杀列表', key: '3-2' },
            { title: '推荐列表', key: '3-3' },
            { title: '筛选列表', key: '3-4' },
          ],
        },
        {
          title: '数据可视化',
          key: '4',
          children: [
            { title: 'echarts使用', key: '4-1' }
          ],
        },
        {
          title: '编辑器',
          key: '5',
          children: [
            { title: '富文本编辑器', key: '5-1' }
          ],
        },
        {
          title: 'excel管理',
          key: '6',
          children: [
            { title: 'excel导入', key: '6-1' },
            { title: 'excel导出', key: '6-2' }
          ],
        },
        {
          title: '地图管理',
          key: '7',
          children: [
            { title: '百度地图', key: '7-1' }
          ],
        },
        
    ];

    return (
        <div className='swiper'>
             <Button onClick={showDrawer} type="primary">添加管理员<PlusOutlined /> </Button>
             <Table loading={loading} className='table' onChange={onPageChange} style={{marginTop:20}} columns={columns} dataSource={adminlist} />
             {/* 抽屉组件 */}
             <Drawer title={adminid?'编辑管理员':'新增管理员'} placement="right" onClose={onClose} open={open}>
                <Form
                    form={form}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    style={{ maxWidth: 600 }}
                    onFinish={onFinish}
                >
                    <Form.Item
                    label="账号"
                    name="adminname"
                    rules={[{ required: true, message: '请输入账号' }]}
                    >
                        <Input disabled={adminid!=''} />
                    </Form.Item>

                    <Form.Item
                    label="密码"
                    name="password"
                    rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input disabled={adminid!=''} />
                    </Form.Item>

                    <Form.Item
                    label="角色"
                    name="role"
                    rules={[{ required: true, message: '请选择角色' }]}
                    >
                        <Select
                        // onChange={handleChange}
                        options={[
                            { value: 1, label: '管理员' },
                            { value: 2, label: '超级管理员' }
                        ]}
                        />
                    </Form.Item>

                    <Form.Item
                    label="权限"
                    name="checkedKeys"
                    rules={[{ required: true, message: '请选择权限' }]}
                    >
                        <Tree
                        checkable
                        onCheck={onCheck}
                        checkedKeys={checkedKeys}
                        treeData={treeData}
                        />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
                        <Button type="primary" htmlType="submit">
                            {adminid?'编辑管理员':'新增管理员'}
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
        </div>
    );
}

export default Admin;